package org.ouwh.oowiki;

import java.io.FileReader;
import java.lang.management.ManagementFactory;
import java.rmi.registry.LocateRegistry;
import java.util.HashMap;
import java.util.Properties;

import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ouwh.fw.model.ModelCore;

public class Startup implements StartupMBean {
	private static Log log = LogFactory.getLog(Startup.class);
	private JMXConnectorServer cs;

	public static void main(String[] args) {
		Startup server = new Startup();
		server.startJmxServer();
		server.run();

	}

	private void startJmxServer() {
		try {
			Properties props = new Properties();
			FileReader in = null;
			try {
				in = new FileReader(System.getProperty("org.ouwh.oowiki.jmxfile", "etc/management.properties"));
				props.load(in);
			} finally {
				try {
					in.close();
				} catch (Exception e) {
				}
			}
			int port = Integer.parseInt(props.getProperty("com.sun.management.jmxremote.port"));
			String tokenPostFix = props.getProperty("com.sun.management.jmxremote.token");
			LocateRegistry.createRegistry(port);
			MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
			HashMap<String, Object> env = new HashMap<String, Object>();
			env.put(JMXConnectorServer.AUTHENTICATOR, new MyJMXAuthenticator(tokenPostFix));
			JMXServiceURL url = new JMXServiceURL(
					"service:jmx:rmi://0.0.0.0:" + port + "/jndi/rmi://0.0.0.0:" + port + "/jmxrmi");
			cs = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
			cs.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void run() {
		try {
			ModelCore.startup(this.getClass());
			MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
			mBeanServer.registerMBean(this,
					new ObjectName(getClass().getPackage().getName() + ":name=" + getClass().getSimpleName()));
			log.info("OO-Wiki server started.");
		} catch (Exception e) {
			log.error("Server boot failed, reason: ", e);
		}
	}

	public void shutdown() {
		ModelCore.shutdown();
		try {
			cs.stop();
		} catch (Exception e) {
			e.printStackTrace();
		}
		log.info("OO-Wiki server stopped.");
	}

}
